/**
* This trigger sets the duplicate flag based on the Lead Company Name 
Version 1.1 Author Sunitha Naik
*/


trigger dupCheck on Lead (before insert) 
{
List<lead> NewLead = new List<Lead>();
List<Lead> DupLeads;
List<Account> DupCompAccounts ;
List<Contact> DupCompContacts ;
List<Account> DupPhoneAccounts ;
List<Contact> DupPhoneContacts ;



/* get the company information entered by the user */
  try
      {

        for(Lead ldNew:Trigger.New)
              {
                     NewLead.add(ldNew);
               }
         system.debug('XXXXXXXXXXX' + NewLead);

        /* check for the existence of ComPany Name in the system */
        for(Lead LD :NewLead){
            //system.debug('VVVVVVVVVVVV' + LD.Company);
            //system.debug('CCCCCCCCCCCCCC' + LD.Phone);
            DupLeads = [Select Id,Company,Phone,DupIndicator__c,Disposition__c from Lead where Company = :LD.Company or Phone = :LD.Phone ];          
            DupCompAccounts = [Select Name from Account where name = :LD.Company];
            DupCompContacts = [Select Name, Account.Name from Contact where Account.Name = :LD.Company];
            DupPhoneAccounts = [Select Phone from Account where Phone = :LD.Phone];
            DupPhoneContacts = [Select Phone from Contact where Phone = :LD.Phone];
            if(DupPhoneAccounts.size() >0 || DupPhoneContacts.size() > 0 ){
                LD.Phone.addError('You cannot create this lead as an Account or Contact with the same Phone No already exist.');
            }
             else if(DupLeads.size()>0 || DupCompAccounts.size() > 0 || DupCompContacts.size() > 0 )
                   {
                           //system.debug('CCCCCCCCCCCCCCYES');
                           LD.Duplicate__c=true;
                           LD.Disposition__c='Duplicate';
                           
                   }
        
        }
    }

catch(Exception e)
{
System.debug('Exception caught is'+e);
}

}